const mongoose = require('mongoose');

const transactionSchema = new mongoose.Schema({
  room: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'Room',
    required: true
  },
  from: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'User',
    required: true
  },
  to: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'User',
    required: true
  },
  amount: {
    type: Number,
    required: true,
    min: 0
  },
  description: {
    type: String,
    trim: true,
    maxlength: 100
  },
  type: {
    type: String,
    enum: ['win', 'lose', 'transfer', 'penalty', 'bonus'],
    default: 'transfer'
  },
  status: {
    type: String,
    enum: ['pending', 'completed', 'cancelled'],
    default: 'completed'
  },
  createdBy: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'User',
    required: true
  }
}, {
  timestamps: true
});

// 索引优化查询性能
transactionSchema.index({ room: 1 });
transactionSchema.index({ from: 1, createdAt: -1 });
transactionSchema.index({ to: 1, createdAt: -1 });

// 获取用户在房间中的交易统计
transactionSchema.statics.getUserStats = async function(userId, roomId) {
  const stats = await this.aggregate([
    {
      $match: {
        room: mongoose.Types.ObjectId(roomId),
        $or: [
          { from: mongoose.Types.ObjectId(userId) },
          { to: mongoose.Types.ObjectId(userId) }
        ],
        status: 'completed'
      }
    },
    {
      $group: {
        _id: null,
        totalWins: {
          $sum: {
            $cond: [
              { $eq: ['$to', mongoose.Types.ObjectId(userId)] },
              '$amount',
              0
            ]
          }
        },
        totalLosses: {
          $sum: {
            $cond: [
              { $eq: ['$from', mongoose.Types.ObjectId(userId)] },
              '$amount',
              0
            ]
          }
        },
        totalTransactions: { $sum: 1 }
      }
    }
  ]);
  
  return stats[0] || { totalWins: 0, totalLosses: 0, totalTransactions: 0 };
};

// 获取房间交易统计
transactionSchema.statics.getRoomStats = async function(roomId) {
  const stats = await this.aggregate([
    {
      $match: {
        room: mongoose.Types.ObjectId(roomId),
        status: 'completed'
      }
    },
    {
      $group: {
        _id: null,
        totalAmount: { $sum: '$amount' },
        totalTransactions: { $sum: 1 }
      }
    }
  ]);
  
  return stats[0] || { totalAmount: 0, totalTransactions: 0 };
};

module.exports = mongoose.model('Transaction', transactionSchema); 